package com.nulldev.util.web.nTube.pages.misc;

import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.time.Duration;
import java.util.Map;

import javax.net.ssl.SSLException;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.concurrency.threadIt.v4.emapi.cntft.ControllableFutureTask;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.web.HttpClient.HttpClient;
import com.nulldev.util.web.HttpClient.HttpResponse;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.ASyncHttpPage3;
import com.nulldev.util.web.URLUtils.URLUtils;
import com.nulldev.util.web.URLUtils.fuckTracking.FuckTracking;

public class ProxyGetDislikesPage extends ASyncHttpPage3 {

	/* PART OF AN EXPERIMENTAL nTube OPTION */
	/* THIS FEATURE MAY BE REMOVED AT ANY TIME */

	/*
	 * Sourced from: https://github.com/Anarios/return-youtube-dislike The above
	 * project was released under the GNU GENERAL PUBLIC LICENSE 3.0
	 */

	private static final Logger log = LoggerFactory.getLoggerD(Arguments.hasArgument("--debug", "--trace"));

	public ProxyGetDislikesPage() {
		super("/api/experimental/get_dislikes");
		super.setCachingMethod(CachingMethod.NO_CACHE);
		super.setUseJSONCaptchaPage(true);
		super.setChecks(EnhancedSecurityChecks.DISALLOW_POST_DATA, EnhancedSecurityChecks.ONLY_ALLOW_BASIC_METHODS);
	}

	@SuppressWarnings("resource")
	@Override
	public void onFutureRequest(final Request request, final ControllableFutureTask<Response> r) {
		final Map<String, String> s = URLUtils.parseQuery(request.url());
		if (s == null) {
			log.error("Query url failed and returned null!");
			r.complete(new Response(503).requestKeepAliveDisable(true));
			return;
		} else if (!s.containsKey("v")) {
			log.debug("Dropped Proxy-Get-Dislikes request: No video ID found.");
			log.debug("Got: " + request.url());
			r.complete(new Response(403));
			return;
		}
		final String videoID = s.get("v");
		try {
			final HttpResponse<InputStream> rx = HttpClient.getStream().url("https://returnyoutubedislikeapi.com/votes?videoId=" + videoID)
					.timeout(Duration.ofSeconds(60)).header("From", "nTube 1.5.0, PGDP").headers(FuckTracking.protect()).create();
			r.complete(new Response(rx.status(), rx, rx));
			return;
		} catch (SocketTimeoutException e) {
			r.complete(new Response(503));
			return;
		} catch (SSLException ex) {
			log.error("Failed to get dislikes, this might be a network issue...");
			r.complete(new Response(503));
			return;
		} catch (Exception e) {
			r.fail(e);
			return;
		}
	}

}
